//
//  XferCalcViewController.m
//  XferCalc
//
//  Created by Nathan Nottingham on 11/21/08.
//  Copyright Blah 2008. All rights reserved.
//

#import "XferCalcViewController.h"
#import "SaveData.h"

@implementation XferCalcViewController

-(void)calcTime {
	long long seconds = (filesize.text.floatValue * sizeValues[sizeMarker]) / speedValues[speedMarker];
	float Fseconds = (filesize.text.floatValue * sizeValues[sizeMarker]) / speedValues[speedMarker];
	
	if (seconds <= 60) {
		outputLabel.text = [NSString stringWithFormat:@"%1.2f seconds", Fseconds];
	} else if (seconds <= 3600) {
		long long minutes = seconds / 60;
		seconds = seconds % 60;
		outputLabel.text = [NSString stringWithFormat:@"%lld minutes\n%lld seconds", minutes, seconds];
	} else if (seconds <= 86400) {
		long long hours = seconds / 3600;
		seconds = seconds % 3600;
		long long minutes = seconds / 60;
		seconds = seconds % 60;
		outputLabel.text = [NSString stringWithFormat:@"%lld hours\n%lld minutes\n%lld seconds", hours, minutes, seconds];
	} else {
		long long days = seconds / 86400;
		seconds = seconds % 86400;
		long long hours = seconds / 3600;
		seconds = seconds % 3600;
		long long minutes = seconds / 60;
		seconds = seconds % 60;
		outputLabel.text = [NSString stringWithFormat:@"%lld days\n%lld hours\n%lld minutes\n%lld seconds", days, hours, minutes, seconds];
	}
	id obid; // object id
	// create autorelease pool
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
	
	// create instance of MyObject
	obid = [[[SaveData alloc]init]autorelease];
	
	// set two strings to instance
	NSString *num1 = filesize.text;
	NSNumber *num2 = [[NSNumber alloc] initWithInt: sizeMarker];
	NSNumber *num3 = [[NSNumber alloc] initWithInt: speedMarker];
	
	[obid setNumber:num1 andNumber:num2 andNumber:num3];
	
	// log strings
		NSLog(@"before:");
		[obid logStrings];
	
	// call keyed archiver
	
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
	NSString *documentsDirectoryPath = [paths objectAtIndex:0];
	NSString *myFilePath = [documentsDirectoryPath stringByAppendingPathComponent:@"saveData.obj"];
	
	if (![NSKeyedArchiver archiveRootObject:obid toFile:myFilePath]) { // . @"saveData.obj"]) {
		NSLog(@"Could not create keyed archive.");
	}
	// release pool
	[pool release];
}

// Implement viewDidLoad to do additional setup after loading the view.
- (void)viewDidLoad {
	
	[super viewDidLoad];	
	[self createSizePicker];
	[self createSpeedPicker];
	
	id obid; // object id
	// create autorelease pool
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
	
	// create instance of MyObject
	obid = [[[SaveData alloc]init]autorelease];

	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
	NSString *documentsDirectoryPath = [paths objectAtIndex:0];
	NSString *myFilePath = [documentsDirectoryPath stringByAppendingPathComponent:@"saveData.obj"];
	
	// unarchive stored file
	obid = [NSKeyedUnarchiver unarchiveObjectWithFile:myFilePath];
	
	// log strings of unarchived object
	NSLog(@"after:");
	[obid logStrings];

	filesize.text = [obid getFileSize];
	sizeMarker    = [obid getUnitSize];
	speedMarker   = [obid getXferSpeed];
	
	[speedButton setTitle:[NSString stringWithFormat:@"%@", [speedArray objectAtIndex:speedMarker]] forState:UIControlStateNormal];
	[sizeButton setTitle:[NSString stringWithFormat:@"%@", [sizeArray objectAtIndex:sizeMarker]] forState:UIControlStateNormal];
	[self calcTime];

	// release pool
	[pool release];
}

- (void)createSpeedPicker {

	speedMarker = 0;
	
	speedArray = [[NSArray arrayWithObjects:
					@"56 Kbps",
					@"128 Kbps",
					@"256 Kbps",
					@"512 Kbps",
					@"768 Kbps",						
					@"1.544 Mbps T1/DS1", 
					@"2.048 Mbps E1",
					@"10 Mbps Thin Ethernet",
					@"44.736 Mbps T3/DS3",
					@"100 Mbps Fast Ethernet",
					@"155.52 Mbps OC-3",						
					@"622.08 Mbps OC-12",
					@"1000 Mbps Gig E",
					nil] retain];
		
	speedValues[0]  = 56000;
	speedValues[1]  = 128000;
	speedValues[2]  = 256000;
	speedValues[3]  = 512000;
	speedValues[4]  = 768000;
	speedValues[5]  = 1544000;
	speedValues[6]  = 2048000;
	speedValues[7]  = 10000000;
	speedValues[8]  = 44736000;
	speedValues[9]  = 100000000;
	speedValues[10] = 155520000;
	speedValues[11] = 622080000;
	speedValues[12] = 1000000000;
	
	// note we are using CGRectZero for the dimensions of our picker view,
	// this is because picker views have a built in optimum size,
	// you just need to set the correct origin in your view.
	//
	// position the picker at the bottom
	speedPickerView = [[UIPickerView alloc] initWithFrame:CGRectZero];
	CGSize pickerSize = [speedPickerView sizeThatFits:CGSizeZero];
	speedPickerView.frame = [self pickerFrameWithSize:pickerSize];
	
	speedPickerView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
	speedPickerView.delegate = self;
	speedPickerView.showsSelectionIndicator = YES;	// note this is default to NO
	
	// add this picker to our view controller, initially hidden
	speedPickerView.hidden = YES;
	[self.view addSubview:speedPickerView];
}

- (void)createSizePicker {

	sizeMarker = 0;
	
	sizeValues[0] = 1;
	sizeValues[1] = 8;
	sizeValues[2] = 8192;
	sizeValues[3] = 8388608;
	sizeValues[4] = 8589934592;
	sizeValues[5] = 8796093022208;
	sizeValues[6] = 9007199254740992;
	
	sizeArray = [[NSArray arrayWithObjects:
				  @"Bits",
				  @"Bytes",
				  @"Kilobytes",
				  @"Megabytes",
				  @"Gigabytes",
				  @"Terabytes",
				  @"Petabytes", 
				  nil] retain];
	
	// note we are using CGRectZero for the dimensions of our picker view,
	// this is because picker views have a built in optimum size,
	// you just need to set the correct origin in your view.
	//
	// position the picker at the bottom
	sizePickerView = [[UIPickerView alloc] initWithFrame:CGRectZero];
	CGSize pickerSize = [sizePickerView sizeThatFits:CGSizeZero];
	sizePickerView.frame = [self pickerFrameWithSize:pickerSize];
	
	sizePickerView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
	sizePickerView.delegate = self;
	sizePickerView.showsSelectionIndicator = YES;	// note this is default to NO
	
	// add this picker to our view controller, initially hidden
	sizePickerView.hidden = YES;
	[self.view addSubview:sizePickerView];
}

// return the picker frame based on its size, positioned at the bottom of the page
- (CGRect)pickerFrameWithSize:(CGSize)size {
	CGRect screenRect = [[UIScreen mainScreen] applicationFrame];
	CGRect pickerRect = CGRectMake(	0.0,
								   screenRect.size.height - size.height,
								   size.width,
								   size.height);
	return pickerRect;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
	if(pickerView == speedPickerView) {
		return [speedArray count];
	} else {
		return [sizeArray count];
	}
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
	return 1;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
	NSString *returnStr;
	if(pickerView == speedPickerView) {
		if (component == 0) {
			returnStr = [speedArray objectAtIndex:row];
		} else {
			returnStr = [[NSNumber numberWithInt:row] stringValue];
		}
		return returnStr;
	} else {
		if (component == 0) {
			returnStr = [sizeArray objectAtIndex:row];
		} else {
			returnStr = [[NSNumber numberWithInt:row] stringValue];
		}
		return returnStr;
	}
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
	return 270.0;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
	return 40.0;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
	if(pickerView == speedPickerView) {
		[speedButton setTitle:[NSString stringWithFormat:@"%@", [speedArray objectAtIndex:[pickerView selectedRowInComponent:0]]] forState:UIControlStateNormal];
		speedMarker = [pickerView selectedRowInComponent:0];
	} else {
		[sizeButton setTitle:[NSString stringWithFormat:@"%@", [sizeArray objectAtIndex:[pickerView selectedRowInComponent:0]]] forState:UIControlStateNormal];
		sizeMarker = [pickerView selectedRowInComponent:0];
	}
	speedPickerView.hidden = YES;
	sizePickerView.hidden = YES;
	[self calcTime];
}

-(void)speedEdit{
	speedPickerView.hidden = NO;
}

-(void)sizeEdit{
	sizePickerView.hidden = NO;
}

-(IBAction)userDoneEnteringText:(id)sender {
	float seconds = filesize.text.floatValue;
	filesize.text = [NSString stringWithFormat:@"%1.2f", seconds];
	[self calcTime];
}

-(IBAction)contactMat:(id)sender {
	NSURL *url = [[NSURL alloc] initWithString:@"http://webdiligence.ca"];
	[[UIApplication sharedApplication] openURL:url];

}

-(IBAction)contactNate:(id)sender {
	NSURL *url = [[NSURL alloc] initWithString:@"mailto://nate@nottingham-tech.com?subject=XferCalc&body=I%20saw%20that%20you%20programmed%20XferCalc%20and%20need%20you%20to%20freelance%20for%20me!"];
	[[UIApplication sharedApplication] openURL:url];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
	// bah!  If this app leaks, I'm going to quit and go into orthodontics..
}

- (void)dealloc {
	[super dealloc];
}

@end
